/**
 * Copilot主面板组件
 * AI智能助手侧边栏
 */

import React, { useEffect, useState } from 'react';
import { Collapse, Badge, Button, Tooltip, Space } from 'antd';
import {
  BulbOutlined,
  CheckCircleOutlined,
  MessageOutlined,
  BookOutlined,
  SettingOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { useCopilotStore } from '@/stores/copilot.store';
import { useEditorStore } from '@/stores/editor.store';
import { SuggestionCard } from './SuggestionCard';
import { ChecklistPanel } from './ChecklistPanel';
import { ChatPanel } from './ChatPanel';
import './style.css';

const { Panel } = Collapse;

export const Copilot: React.FC = () => {
  const {
    suggestions,
    quickActions,
    checklist,
    checklistProgress,
    references,
    chatHistory,
    chatLoading,
    isPanelVisible,
    isPanelCollapsed,
    fetchSuggestions,
    applySuggestion,
    removeSuggestion,
    updateChecklist,
    fetchReferences,
    citeReference,
    sendChatMessage,
    insertChatResponse,
    clearChatHistory,
    togglePanel,
  } = useCopilotStore();

  const { content, selectedText, cursorPosition } = useEditorStore();

  const [activeKeys, setActiveKeys] = useState<string[]>(['suggestions', 'checklist']);

  // 定期更新建议
  useEffect(() => {
    if (!isPanelVisible) return;

    const interval = setInterval(() => {
      const context = {
        currentText: content,
        selectedText,
        cursorPosition,
        previousParagraphs: content.split('\n\n').slice(-3),
        nextParagraphs: [],
        wordCount: content.length,
      };

      fetchSuggestions(context);
      updateChecklist(context);
    }, 5000); // 每5秒更新一次

    return () => clearInterval(interval);
  }, [isPanelVisible, content, selectedText, cursorPosition]);

  if (!isPanelVisible) {
    return (
      <div className="copilot-toggle-btn">
        <Tooltip title="显示AI Copilot" placement="left">
          <Button
            type="primary"
            shape="circle"
            icon={<BulbOutlined />}
            size="large"
            onClick={togglePanel}
          />
        </Tooltip>
      </div>
    );
  }

  return (
    <div className="copilot-panel">
      {/* 头部 */}
      <div className="copilot-header">
        <Space>
          <BulbOutlined style={{ fontSize: 20, color: '#1890ff' }} />
          <h3>AI Copilot</h3>
        </Space>
        <Space>
          <Tooltip title="设置">
            <Button
              type="text"
              size="small"
              icon={<SettingOutlined />}
            />
          </Tooltip>
          <Tooltip title="隐藏">
            <Button
              type="text"
              size="small"
              icon={<EyeInvisibleOutlined />}
              onClick={togglePanel}
            />
          </Tooltip>
        </Space>
      </div>

      {/* 快速操作卡片 */}
      {quickActions.length > 0 && (
        <div className="quick-actions-section">
          <div className="section-title">
            <span>快速操作</span>
            <Badge count={quickActions.length} />
          </div>
          <div className="quick-actions-grid">
            {quickActions.map((action) => (
              <div
                key={action.id}
                className="quick-action-card"
                onClick={() => applySuggestion(action.id)}
              >
                <span className="quick-action-icon">{action.icon}</span>
                <span className="quick-action-text">{action.title}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 主内容 */}
      <div className="copilot-content">
        <Collapse
          activeKey={activeKeys}
          onChange={(keys) => setActiveKeys(keys as string[])}
          bordered={false}
          expandIconPosition="end"
        >
          {/* 写作建议 */}
          <Panel
            header={
              <Space>
                <BulbOutlined />
                <span>写作建议</span>
                <Badge count={suggestions.length} showZero />
              </Space>
            }
            key="suggestions"
          >
            <div className="suggestions-list">
              {suggestions.length > 0 ? (
                suggestions.map((suggestion) => (
                  <SuggestionCard
                    key={suggestion.id}
                    suggestion={suggestion}
                    onApply={applySuggestion}
                    onDismiss={removeSuggestion}
                  />
                ))
              ) : (
                <div className="empty-state">
                  <p>暂无建议</p>
                  <p className="empty-hint">继续写作，我会实时提供建议</p>
                </div>
              )}
            </div>
          </Panel>

          {/* 质量检查清单 */}
          <Panel
            header={
              <Space>
                <CheckCircleOutlined />
                <span>质量检查</span>
                <Badge count={`${checklistProgress}%`} color={checklistProgress > 70 ? 'green' : 'orange'} />
              </Space>
            }
            key="checklist"
          >
            <ChecklistPanel
              items={checklist}
              progress={checklistProgress}
              onItemClick={(item) => {
                console.log('Jump to position:', item.position);
                // TODO: 跳转到对应位置
              }}
            />
          </Panel>

          {/* 对话助手 */}
          <Panel
            header={
              <Space>
                <MessageOutlined />
                <span>对话助手</span>
                <Badge count={chatHistory.filter((m) => m.role === 'assistant').length} />
              </Space>
            }
            key="chat"
          >
            <ChatPanel
              messages={chatHistory}
              loading={chatLoading}
              onSendMessage={sendChatMessage}
              onInsertMessage={insertChatResponse}
              onClearHistory={clearChatHistory}
            />
          </Panel>

          {/* 参考资料 */}
          <Panel
            header={
              <Space>
                <BookOutlined />
                <span>参考资料</span>
                <Badge count={references.length} />
              </Space>
            }
            key="references"
          >
            <div className="references-list">
              {references.length > 0 ? (
                references.map((ref) => (
                  <div key={ref.id} className="reference-card">
                    <h4 className="reference-title">{ref.title}</h4>
                    <p className="reference-summary">{ref.summary}</p>
                    <div className="reference-meta">
                      <Space size="small">
                        <span className="reference-source">{ref.source}</span>
                        <span className="reference-credibility">
                          可信度: {ref.credibility}%
                        </span>
                        <span className="reference-relevance">
                          相关度: {ref.relevance}%
                        </span>
                      </Space>
                    </div>
                    <div className="reference-actions">
                      <Button
                        type="link"
                        size="small"
                        onClick={() => citeReference(ref.id)}
                      >
                        引用
                      </Button>
                      {ref.url && (
                        <Button
                          type="link"
                          size="small"
                          href={ref.url}
                          target="_blank"
                        >
                          查看原文
                        </Button>
                      )}
                    </div>
                  </div>
                ))
              ) : (
                <div className="empty-state">
                  <p>暂无参考资料</p>
                  <Button
                    type="primary"
                    size="small"
                    onClick={() => {
                      const query = selectedText || content.slice(0, 50);
                      fetchReferences(query);
                    }}
                  >
                    搜索相关资料
                  </Button>
                </div>
              )}
            </div>
          </Panel>
        </Collapse>
      </div>
    </div>
  );
};
